import socket
import time

DEVICEID = "2795"
APIKEY = "d843dc6d8"
host = "www.bigiot.net"
port = 8181

def connect_bigiot(s):
    # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("connection bigiot.net")
    addr = socket.getaddrinfo(host, port)[0][-1]
    try:
        print("connection beike success")
        s.connect(addr)
    except:
        print('Waiting for connect bigiot.net')

    print('Connect bigiot success!')
    # 获取会话返回信息
    ans = s.recv(50)
    print(ans)
    online(s)

def keepOnline(s, t):
    if time.time()-t > 40 or True:
        # sayBytes = bytes('{\"M\":\"status\"}\n', 'utf8')
        # s.sendall(sayBytes)
        online(s)
        return time.time()
    else:
        return t

# 连接至贝壳物联后，需要通过发送命令，使得设备上线
def online(s):
    checkinBytes = bytes('{\"M\":\"checkin\",\"ID\":\"' + DEVICEID + '\",\"K\":\"' + APIKEY + '\"}\n', 'utf8')
    s.sendall(checkinBytes)
    print('send onlie !')